package org.example.demo01.service;

import org.example.demo01.dto.WorkStationQueueDTO;
import org.example.demo01.entity.Dispatch;
import org.example.demo01.entity.Piece;
import org.example.demo01.entity.Process;
import org.example.demo01.entity.Product;
import org.example.demo01.repository.DispatchRepository;
import org.example.demo01.repository.PieceRepository;
import org.example.demo01.repository.ProcessRepository;
import org.example.demo01.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class WorkStationService {

    private final DispatchRepository dispatchRepository;
    private final PieceRepository pieceRepository;
    private final ProcessRepository processRepository;
    private final ProductRepository productRepository;

    @Autowired
    public WorkStationService(DispatchRepository dispatchRepository,
                              PieceRepository pieceRepository,
                              ProcessRepository processRepository,
                              ProductRepository productRepository) {
        this.dispatchRepository = dispatchRepository;
        this.pieceRepository = pieceRepository;
        this.processRepository = processRepository;
        this.productRepository = productRepository;
    }

    public List<WorkStationQueueDTO> getWorkstationQueueByid(String wsid) {
        // 新添加的自定义查询方法
        List<Dispatch> dispatches = dispatchRepository.findListByWsidAndStatus(wsid, 1);

        List<WorkStationQueueDTO> queue = new ArrayList<>();

        for (Dispatch dispatch : dispatches) {
            Optional<Piece> pieceOptional = pieceRepository.findById(dispatch.getPieid());
            if (!pieceOptional.isPresent()) continue;

            Piece piece = pieceOptional.get();
            Optional<Product> productOptional = productRepository.findById(piece.getPid());
            if (!productOptional.isPresent()) continue;

            Product product = productOptional.get();
            Process process = processRepository.findByPidAndWsid(piece.getPid(), wsid);
            if (process == null) continue;

            WorkStationQueueDTO dto = new WorkStationQueueDTO();
            dto.setQueueNumber(dispatch.getQid());
            dto.setPieceId(piece.getId());
            dto.setProductId(product.getId());
            dto.setProductName(product.getName());
            dto.setEstimatedTime(Integer.parseInt(process.getElapsed()));
            dto.setRemarks("");

            queue.add(dto);
        }

        return queue.stream()
                .sorted(Comparator.comparing(dto -> Integer.parseInt(dto.getQueueNumber())))
                .collect(Collectors.toList());
    }
}